﻿using Avalon.Core.MVC.Actions;
using Avalon.Core.MVC.StateBags;
using Avalon.Core.Providers;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;

namespace Avalon.Core.MVC.Pipelines {
    /// <summary>
    /// Use this base pipeline in order to facilitate the creation and handling of pipelines.
    /// </summary>
    public abstract class BasePipeline : IPipeline {
        /// <summary>
        /// The statebag
        /// </summary>
        public IStateBag StateBag { get; set; }

        /// <summary>
        /// The pipeline actions
        /// </summary>
        public ICollection<IPipelineAction> PipelineActions { get; set; }

        /// <summary>
        /// CTOR
        /// </summary>
        public BasePipeline() {
            //newup the pipeline actions.
            PipelineActions = new HashSet<IPipelineAction>();
            //newup the statebag. This can be overridden in order to create custom statebag implementations.
            InitializeStateBag();
        }

        /// <summary>
        /// Initialize the statebag. Override for custom statebag implementations
        /// </summary>
        public virtual void InitializeStateBag() {
            if (StateBag == null) StateBag = new StateBag();
        }

        /// <summary>
        /// Execute the pipeline.
        /// </summary>
        public void Execute() {
            foreach (IPipelineAction action in PipelineActions.OrderBy(p => p.Index)) {
                action.Execute(StateBag);
            }
        }

        protected void addParameter(string key) {
            string value = HttpContext.Current.Request.QueryString[key];
            if (value == null) {
                RequestContext requestContext = ContextProvider.RequestContext;
                if (requestContext.RouteData.Values.ContainsKey(key)) {
                    value = requestContext.RouteData.Values[key].ToString();
                }
            }

            this.StateBag.ParameterValues.Add(key, value);
        }
    }
}
